#include "fsm_timer.h"
#include "Bsp.h"

static fsm_timer_t fsm_timer_defunct;
static fsm_timer_t *fsm_current_timer = 0;

extern void fsm_timer_msg(uint32_t addr);

/*********************************  定时函数  *******************************/
void fsm_timer_init(fsm_timer_t *timer, timer_func entry, uint32_t nTicks, timer_ctr flg)
{
    // 初始化链表
    rt_list_init(&timer->tlist);
    
    // 定时设置
    timer->ctr = flg;
    timer->nTicks = 0;
    timer->interval = nTicks;
    
    // 回调函数
    timer->entry = entry;

    // 添加到列表
    rt_list_insert_before(&fsm_timer_defunct.tlist, &timer->tlist);
}

void fsm_timer_set(fsm_timer_t *timer, uint32_t nTicks, timer_ctr flg)
{
    Bsp_hw_interrupt_disable();

    timer->ctr = flg;
    timer->nTicks = nTicks;
    timer->interval = nTicks;

    Bsp_hw_interrupt_enable();
}

int fsm_timer_start(fsm_timer_t *timer, uint32_t nTicks)
{
    Bsp_hw_interrupt_disable();

    timer->nTicks = nTicks;
    
    Bsp_hw_interrupt_enable();
    
    return 1;
}

int fsm_timer_stop(fsm_timer_t *timer)
{
    Bsp_hw_interrupt_disable();

    timer->nTicks = 0;
    
    Bsp_hw_interrupt_enable();
    
    return 1;
}

void fsm_system_timer_init(uint32_t nTicks)
{
    fsm_timer_init(&fsm_timer_defunct, fsm_system_timer, nTicks, fsm_timer_period_flg);
    fsm_timer_start(&fsm_timer_defunct, nTicks);
}

void fsm_timer_handler(void)
{
    rt_list_t *list = &fsm_timer_defunct.tlist;
    
    do
    {
        fsm_current_timer = rt_list_entry(list, fsm_timer_t, tlist);

        if (fsm_current_timer->nTicks)
        {
            fsm_current_timer->nTicks --;
            if(fsm_current_timer->nTicks == 0)
            {
                if (fsm_current_timer->ctr == fsm_timer_period_flg) {
                    fsm_current_timer->nTicks = fsm_current_timer->interval;
                }
                
                // 给默认线程发消息
                fsm_timer_msg((uint32_t)fsm_current_timer->entry);
            }
        }
        // else
        // {
        //     // 清理失效定时器
        //     list = list->prev;
        //     rt_list_remove(list->next);
        // }

        // 下一个节点
        list = list->next;
    } while (list != &fsm_timer_defunct.tlist);
}
